package com.example.library;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.library.adapter.SingleRoomAdapter;
import com.example.library.model.SingleRoom;
import com.example.library.util.LocalStorageManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SingleRoomsActivity extends AppCompatActivity implements SingleRoomAdapter.OnRoomClickListener {

    private static final String TAG = "SingleRoomsActivity";
    private RecyclerView recyclerView;
    private SingleRoomAdapter adapter;
    private List<SingleRoom> roomList;
    private LocalStorageManager storageManager;
    private boolean isAdmin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_rooms);

        // 获取是否是管理员
        isAdmin = getIntent().getBooleanExtra("isAdmin", false);
        Log.d(TAG, "Is admin mode: " + isAdmin);

        // 初始化本地存储管理器
        storageManager = new LocalStorageManager(this);

        // 设置Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));

        // 初始化房间列表
        roomList = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            roomList.add(new SingleRoom(String.format("S%02d", i)));
        }

        // 从本地存储加载房间状态
        loadRoomStates();

        adapter = new SingleRoomAdapter(roomList, this, isAdmin);
        recyclerView.setAdapter(adapter);
    }

    private void loadRoomStates() {
        Map<String, LocalStorageManager.SeatInfo> savedStates = storageManager.getSingleRoomsStatus();
        for (SingleRoom room : roomList) {
            LocalStorageManager.SeatInfo info = savedStates.get(room.getRoomNumber());
            if (info != null) {
                room.setStatus(info.getStatus());
                room.setUserId(info.getUserId());
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRoomClick(SingleRoom room) {
        Log.d(TAG, "Room clicked, isAdmin: " + isAdmin);
        if (isAdmin) {
            showAdminDialog(room);
        } else if (!room.isClosedForUse()) {
            showStudentDialog(room);
        }
    }

    private void showAdminDialog(final SingleRoom room) {
        Log.d(TAG, "Showing admin dialog for room: " + room.getRoomNumber());
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.admin_seat_management);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().setLayout((int)(getResources().getDisplayMetrics().widthPixels * 0.9),
                dialog.getWindow().getAttributes().height);

        TextView tvSeatNumber = dialog.findViewById(R.id.tvSeatNumber);
        TextView tvStatus = dialog.findViewById(R.id.tvStatus);
        Button btnStart = dialog.findViewById(R.id.btnStart);
        Button btnClose = dialog.findViewById(R.id.btnClose);

        if (tvSeatNumber == null || tvStatus == null || btnStart == null || btnClose == null) {
            Log.e(TAG, "Failed to find views in admin dialog");
            Toast.makeText(this, "加载管理员界面失败", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
            return;
        }

        tvSeatNumber.setText("单人研修室：" + room.getRoomNumber());
        tvStatus.setText("状态：" + room.getStatus());

        // 根据房间状态设置按钮状态
        if (room.isClosedForUse()) {
            btnStart.setEnabled(true);
            btnClose.setEnabled(false);
        } else {
            btnStart.setEnabled(false);
            btnClose.setEnabled(true);
        }

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                room.setStatus("空闲");
                room.setUserId(null);
                storageManager.saveSingleRoomStatus(room.getRoomNumber(), room.getStatus(), null);
                adapter.notifyDataSetChanged();
                Toast.makeText(SingleRoomsActivity.this, "已开启使用", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                room.setStatus("关闭使用");
                room.setUserId(null);
                storageManager.saveSingleRoomStatus(room.getRoomNumber(), room.getStatus(), null);
                adapter.notifyDataSetChanged();
                Toast.makeText(SingleRoomsActivity.this, "已关闭使用", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    private void showStudentDialog(final SingleRoom room) {
        Log.d(TAG, "Showing student dialog for room: " + room.getRoomNumber());
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.student_seat_reservation);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().setLayout((int)(getResources().getDisplayMetrics().widthPixels * 0.9),
                dialog.getWindow().getAttributes().height);

        TextView tvSeatNumber = dialog.findViewById(R.id.tvSeatNumber);
        TextView tvStatus = dialog.findViewById(R.id.tvStatus);
        Button btnReserve = dialog.findViewById(R.id.btnReserve);
        Button btnCancel = dialog.findViewById(R.id.btnCancel);

        tvSeatNumber.setText("单人研修室：" + room.getRoomNumber());
        tvStatus.setText("状态：" + room.getStatus());

        if (room.isAvailable()) {
            btnReserve.setText("预约");
            btnReserve.setEnabled(true);
            btnCancel.setEnabled(false);
        } else {
            btnReserve.setText("已预约");
            btnReserve.setEnabled(false);
            btnCancel.setEnabled(true);
        }

        btnReserve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                room.setStatus("已预约");
                String userId = "current_user_id"; // 这里需要替换为实际的用户ID
                room.setUserId(userId);
                storageManager.saveSingleRoomStatus(room.getRoomNumber(), room.getStatus(), userId);
                adapter.notifyDataSetChanged();
                Toast.makeText(SingleRoomsActivity.this, "预约成功", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                room.setStatus("空闲");
                room.setUserId(null);
                storageManager.saveSingleRoomStatus(room.getRoomNumber(), room.getStatus(), null);
                adapter.notifyDataSetChanged();
                Toast.makeText(SingleRoomsActivity.this, "已取消预约", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });

        dialog.show();
    }
} 